/**
 * 统一计时器服务 - 整合Web Worker和兼容性处理
 */

import workerManager from './workerManager'
import { createCompatibleTimer, createVisibilityHandler, createPerformanceMonitor } from './timerCompatibility'
import h5plusBackgroundManager, { isH5PlusApp } from './h5plusBackground'

class TimerService {
  constructor() {
    this.timers = new Map()
    this.countdowns = new Map()
    this.workerManager = workerManager
    this.compatibilityTimer = null
    this.visibilityHandler = createVisibilityHandler()
    this.performanceMonitor = createPerformanceMonitor()
    this.isWorkerAvailable = false
    this.fallbackMode = false
    
    // 不在构造函数中调用异步方法，而是通过外部调用init()
  }

  // 初始化服务
  async init() {
    try {
      // 尝试初始化Worker
      await this.workerManager.init()
      this.isWorkerAvailable = true
      this.setupWorkerHandlers()
      console.log('TimerService: 使用Web Worker模式')
    } catch (error) {
      console.warn('TimerService: Worker初始化失败，使用降级模式:', error)
      this.fallbackMode = true
      this.compatibilityTimer = createCompatibleTimer()
      this.setupFallbackHandlers()
    }

    // 设置页面可见性监听
    this.setupVisibilityHandling()
    
    // 初始化H5+ App后台运行支持
    if (isH5PlusApp()) {
      try {
        await h5plusBackgroundManager.init()
        console.log('TimerService: H5+ App后台运行支持已初始化')
      } catch (error) {
        console.warn('TimerService: H5+ App后台运行支持初始化失败:', error)
      }
    }
  }

  // 设置Worker消息处理器
  setupWorkerHandlers() {
    // 计时器更新
    this.workerManager.on('TIMER_UPDATE', (id, data) => {
      const timer = this.timers.get(id)
      if (timer && timer.onUpdate) {
        timer.onUpdate(data.elapsed)
      }
    })

    // 倒计时更新
    this.workerManager.on('COUNTDOWN_UPDATE', (id, data) => {
      const countdown = this.countdowns.get(id)
      if (countdown && countdown.onUpdate) {
        countdown.onUpdate(data.remaining)
      }
    })

    // 倒计时完成
    this.workerManager.on('COUNTDOWN_COMPLETED', (id, data) => {
      const countdown = this.countdowns.get(id)
      if (countdown && countdown.onComplete) {
        countdown.onComplete()
        this.countdowns.delete(id)
      }
    })

    // 各种状态更新
    this.workerManager.on('TIMER_STARTED', (id, data) => {
      const timer = this.timers.get(id)
      if (timer && timer.onStart) {
        timer.onStart()
      }
    })

    this.workerManager.on('TIMER_PAUSED', (id, data) => {
      const timer = this.timers.get(id)
      if (timer && timer.onPause) {
        timer.onPause()
      }
    })

    this.workerManager.on('TIMER_RESUMED', (id, data) => {
      const timer = this.timers.get(id)
      if (timer && timer.onResume) {
        timer.onResume()
      }
    })

    this.workerManager.on('TIMER_STOPPED', (id, data) => {
      const timer = this.timers.get(id)
      if (timer && timer.onStop) {
        timer.onStop()
        this.timers.delete(id)
      }
    })

    this.workerManager.on('COUNTDOWN_STARTED', (id, data) => {
      const countdown = this.countdowns.get(id)
      if (countdown && countdown.onStart) {
        countdown.onStart()
      }
    })

    this.workerManager.on('COUNTDOWN_PAUSED', (id, data) => {
      const countdown = this.countdowns.get(id)
      if (countdown && countdown.onPause) {
        countdown.onPause()
      }
    })

    this.workerManager.on('COUNTDOWN_RESUMED', (id, data) => {
      const countdown = this.countdowns.get(id)
      if (countdown && countdown.onResume) {
        countdown.onResume()
      }
    })

    this.workerManager.on('COUNTDOWN_STOPPED', (id, data) => {
      const countdown = this.countdowns.get(id)
      if (countdown && countdown.onStop) {
        countdown.onStop()
        this.countdowns.delete(id)
      }
    })
  }

  // 设置降级模式处理器
  setupFallbackHandlers() {
    // 降级模式下的处理逻辑
    console.log('TimerService: 降级模式处理器已设置')
  }

  // 设置页面可见性处理
  setupVisibilityHandling() {
    this.visibilityHandler.onVisibilityChange(() => {
      const isVisible = this.visibilityHandler.isVisible()
      // console.log(`TimerService: 页面可见性变化: ${isVisible ? '可见' : '隐藏'}`)
      
      // 可以在这里添加页面可见性变化时的处理逻辑
      if (isVisible) {
        // 页面变为可见时，可以同步Worker状态
        this.syncWorkerState()
      }
    })
  }

  // 同步Worker状态
  syncWorkerState() {
    if (!this.isWorkerAvailable) return
    
    // 同步所有活跃的计时器状态
    for (const [id, timer] of this.timers) {
      if (timer.isRunning) {
        this.workerManager.getStatus(id)
      }
    }
    
    for (const [id, countdown] of this.countdowns) {
      if (countdown.isRunning) {
        this.workerManager.getStatus(id)
      }
    }
  }

  // 创建计时器
  createTimer(options = {}) {
    const id = `timer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    const timer = {
      id,
      isRunning: false,
      isPaused: false,
      startTime: 0,
      pausedTime: 0,
      elapsed: 0,
      onUpdate: options.onUpdate || (() => {}),
      onStart: options.onStart || (() => {}),
      onPause: options.onPause || (() => {}),
      onResume: options.onResume || (() => {}),
      onStop: options.onStop || (() => {}),
      
      start: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.startTimer(id, {})
          // 在Worker模式下也直接调用回调，确保状态立即更新
          timer.onStart()
        } else if (this.compatibilityTimer) {
          // 降级模式
          const result = this.compatibilityTimer.start(() => {
            timer.elapsed++
            timer.onUpdate(timer.elapsed)
          }, 1000)
          if (result) {
            timer.intervalId = result.id
            timer.isRunning = true
            timer.startTime = Date.now()
            timer.onStart()
          }
        }
      },
      
      pause: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.pauseTimer(id)
          // 在Worker模式下也直接调用回调，确保状态立即更新
          timer.onPause()
        } else if (this.compatibilityTimer && timer.intervalId) {
          this.compatibilityTimer.pause(timer.intervalId)
          timer.isPaused = true
          timer.pausedTime += Date.now() - timer.startTime
          timer.onPause()
        }
      },
      
      resume: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.resumeTimer(id)
          // 在Worker模式下也直接调用回调，确保状态立即更新
          timer.onResume()
        } else if (this.compatibilityTimer && timer.intervalId) {
          this.compatibilityTimer.resume(timer.intervalId)
          timer.isPaused = false
          timer.startTime = Date.now()
          timer.onResume()
        }
      },
      
      stop: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.stopTimer(id)
          // 在Worker模式下也直接调用回调，确保状态立即更新
          timer.onStop()
        } else if (this.compatibilityTimer && timer.intervalId) {
          this.compatibilityTimer.stop(timer.intervalId)
          timer.isRunning = false
          timer.isPaused = false
          timer.onStop()
        }
      }
    }
    
    this.timers.set(id, timer)
    return timer
  }

  // 创建倒计时
  createCountdown(options = {}) {
    const id = `countdown_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    const countdown = {
      id,
      duration: options.duration || 60,
      remaining: options.duration || 60,
      isRunning: false,
      isPaused: false,
      startTime: 0,
      pausedTime: 0,
      onUpdate: options.onUpdate || (() => {}),
      onStart: options.onStart || (() => {}),
      onPause: options.onPause || (() => {}),
      onResume: options.onResume || (() => {}),
      onStop: options.onStop || (() => {}),
      onComplete: options.onComplete || (() => {}),
      
      start: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.startCountdown(id, { duration: countdown.duration })
        } else if (this.compatibilityTimer) {
          // 降级模式
          const result = this.compatibilityTimer.start(() => {
            countdown.remaining--
            countdown.onUpdate(countdown.remaining)
            
            if (countdown.remaining <= 0) {
              countdown.onComplete()
              this.countdowns.delete(id)
            }
          }, 1000)
          
          if (result) {
            countdown.intervalId = result.id
            countdown.isRunning = true
            countdown.startTime = Date.now()
            countdown.onStart()
          }
        }
      },
      
      pause: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.pauseCountdown(id)
        } else if (this.compatibilityTimer && countdown.intervalId) {
          this.compatibilityTimer.pause(countdown.intervalId)
          countdown.isPaused = true
          countdown.pausedTime += Date.now() - countdown.startTime
          countdown.onPause()
        }
      },
      
      resume: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.resumeCountdown(id)
        } else if (this.compatibilityTimer && countdown.intervalId) {
          this.compatibilityTimer.resume(countdown.intervalId)
          countdown.isPaused = false
          countdown.startTime = Date.now()
          countdown.onResume()
        }
      },
      
      stop: () => {
        if (this.isWorkerAvailable) {
          this.workerManager.stopCountdown(id)
        } else if (this.compatibilityTimer && countdown.intervalId) {
          this.compatibilityTimer.stop(countdown.intervalId)
          countdown.isRunning = false
          countdown.isPaused = false
          countdown.onStop()
        }
      }
    }
    
    this.countdowns.set(id, countdown)
    return countdown
  }

  // 获取服务状态
  getStatus() {
    return {
      isWorkerAvailable: this.isWorkerAvailable,
      fallbackMode: this.fallbackMode,
      activeTimers: this.timers.size,
      activeCountdowns: this.countdowns.size,
      workerState: this.isWorkerAvailable ? this.workerManager.getWorkerState() : 'not_available',
      h5plusBackground: h5plusBackgroundManager.getBackgroundStatus()
    }
  }

  // 清理所有计时器
  cleanup() {
    // 清理Worker
    if (this.isWorkerAvailable) {
      this.workerManager.cleanup()
    }
    
    // 清理降级模式计时器
    if (this.compatibilityTimer) {
      for (const [id, timer] of this.timers) {
        if (timer.intervalId) {
          this.compatibilityTimer.stop(timer.intervalId)
        }
      }
      for (const [id, countdown] of this.countdowns) {
        if (countdown.intervalId) {
          this.compatibilityTimer.stop(countdown.intervalId)
        }
      }
    }
    
    // 清理可见性监听器
    this.visibilityHandler.removeListener()
    
    // 清理H5+ App后台运行支持
    if (isH5PlusApp()) {
      h5plusBackgroundManager.cleanup()
    }
    
    // 清空集合
    this.timers.clear()
    this.countdowns.clear()
  }
}

// 创建单例实例
const timerService = new TimerService()

export default timerService
